import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
import { Box3 ,Vector3,BackSide,DoubleSide} from 'three'
export default class LoadModel {
    constructor() {
        let dracoLoader = new DRACOLoader();
        dracoLoader.setDecoderPath('./draco/');
        this.gltfLoader = new GLTFLoader();
        this.gltfLoader.setDRACOLoader(dracoLoader);
     }

     loadGlbModel(data){
        return new Promise((resolve,reject)=>{
            this.gltfLoader.load(data.url,(gltf)=>{
                gltf.scene.name = data.name;
                gltf.scene.traverse((child)=>{
                    if(child.isMesh){
                        child.castShadow = true;
                        child.receiveShadow = true;
                        if(data.type == 'MAP'&&child.name.includes('地面')){
                            child.castShadow = false;
                        }
                        child.material.side = DoubleSide;
                        child.material.shadowSide = BackSide;
                    }
                })
                let obox = new Box3().setFromObject(gltf.scene)
                let center = new Vector3();
                obox.getCenter(center);
                const xSize = (obox.max.x - obox.min.x)
                const ySize = (obox.max.y - obox.min.y)
                const zSize = (obox.max.z - obox.min.z)
                const maxDim = Math.max(xSize, ySize, zSize)
                const scale = data.maxsize / maxDim
                gltf.scene.scale.set(scale,scale,scale)
                let obox2 = new Box3().setFromObject(gltf.scene)
                let center2 = new Vector3();
                obox2.getCenter(center2);
                gltf.scene.position.set(data.position.x - center2.x,(data.position.y - center2.y)+(obox2.max.y-obox2.min.y)/2,data.position.z - center2.z)
                gltf.scene.updateMatrixWorld();
                resolve(gltf.scene)
            }, function (xhr) {
                let str = (xhr.loaded / xhr.total * 100).toFixed(2) + "%"
            }, function (err) {
                reject(`${data.name}模型加载出错：${err}`)
            })
        })
     }

     getCenter(model) {
        if (model.isMesh||model.isGroup||model.isObject) {
            let box = new Box3().setFromObject(model)
            let center = new Vector3();
            box.getCenter(center);
            return center
        }
        return null
    }

    getMaxSize(model) {
        if (model.isMesh||model.isGroup||model.isObject) {
            let box = new Box3().setFromObject(model)
            const xSize = (box.max.x - box.min.x)
            const ySize = (box.max.y - box.min.y)
            const zSize = (box.max.z - box.min.z)
            return Math.max(xSize, ySize, zSize)
        }
        return null
    }
}